const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

exports.main = async (event) => {
  const { openid, userInfo } = event; // 传入 openid 和用户基本信息
  const transaction = await db.startTransaction();

  try {
    const utcNow = new Date(); // 云函数中获取的 UTC 时间
    const beijingTime = new Date(utcNow.getTime() + 8 * 60 * 60 * 1000);
    beijingTime.setHours(0, 0, 0, 0);
    
    // 1. 查询今天是否已打卡
    const existingCheckin = await transaction.collection('checkins_info')
      .where({
        openid,
        checkinDate: db.command.gte(beijingTime),
      })
      .get();

    if (existingCheckin.data.length > 0) {
      return { success: false, message: '知道了，你还活着' };
    }

    // 2. 添加打卡记录
    await transaction.collection('checkins_info').add({
      data: {
        openid,
        checkinDate: new Date(),
      }
    });

    // 3. 查询是否已有用户
    const userDoc = await transaction.collection('user_info').where({ openid }).get();
    const now = new Date();

    let resultUser;

    if (userDoc.data.length > 0) {
      const user = userDoc.data[0];
      const updatedDaysAlive = (user.daysAlive || 0) + 1;

      await transaction.collection('user_info').doc(user._id).update({
        data: {
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          lastCheckinDate: now,
          daysAlive: updatedDaysAlive,
          isAlive: true,
          quote: userInfo.quote,
        }
      });

      resultUser = {
        ...user,
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        lastCheckinDate: now,
        daysAlive: updatedDaysAlive,
        isAlive: true,
        quote: userInfo.quote,
      };

    } else {
      // 新用户创建
      const newUser = {
        openid,
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        firstCheckinDate: now,
        lastCheckinDate: now,
        isAlive: true,
        daysAlive: 1,
        quote: userInfo.quote,
      };

      await transaction.collection('user_info').add({ data: newUser });
      resultUser = newUser;
    }

    await transaction.commit();

    return {
      success: true,
      userInfo: resultUser
    };

  } catch (err) {
    await transaction.rollback();
    return { success: false, message: err.message };
  }
};
